package com.youlai.boot.system.listener;
import java.time.LocalDateTime;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.github.likavn.eventbus.core.annotation.EventbusListener;
import com.github.likavn.eventbus.core.api.MsgDelayListener;
import com.github.likavn.eventbus.core.metadata.data.Message;
import com.youlai.boot.shared.websocket.model.ChatMessage;
import com.youlai.boot.system.mapper.LpsOrderDownloadMapper;
import com.youlai.boot.system.mapper.LpsOrderMapper;
import com.youlai.boot.system.model.entity.LpsOrder;
import com.youlai.boot.system.model.entity.LpsOrderDownload;
import com.youlai.boot.system.model.entity.User;
import com.youlai.boot.system.model.vo.LpsOrderNODownloadVO;
import com.youlai.boot.system.service.LpsOrderDownloadService;
import com.youlai.boot.system.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 订阅延时消息
 * 继承接口【MsgDelayListener】并设置监听的消息实体对象
 */
@Component
@EventbusListener(codes = "saveLpsOrder")
@Slf4j
public class DemoDelayMsgListener implements MsgDelayListener<Long> {
    @Resource
    private UserService userService;

    @Resource
    private LpsOrderMapper lpsOrderMapper;

    @Resource
    private LpsOrderDownloadMapper lpsOrderDownloadMapper;

    @Resource
    private LpsOrderDownloadService lpsOrderDownloadService;
    @Resource
    private SimpMessagingTemplate messagingTemplate;
    private final static String DESTINATION = "/queue/greeting";
    private final static String SENDER = "root";

    // 接收业务消息体对象数据
    @Override
    public void onMessage(Message<Long> message) {
        // 增加空值检查
        if (message == null || message.getBody() == null) {
            log.error("收到空消息或消息体为空");
            return;
        }

        Long orderId = message.getBody();
        LpsOrder lpsOrder = lpsOrderMapper.selectById(orderId);
        if (Objects.isNull(lpsOrder)){
            log.error("订单已被删除：{}", orderId);
            return;
        }
        log.info("收到订单下载提醒消息：{}", lpsOrder);
        List<Integer> orderTypeList = JSONUtil.toList(lpsOrder.getOrderType(), Integer.class);
        // 查询拥有弹窗提醒菜单的用户

        List<User> userList = userService.getUserList();
        userList = userList.stream().filter(user -> CollUtil.containsAny(orderTypeList, JSONUtil.toList(user.getOrderType(), Integer.class))).collect(Collectors.toList());
        if (CollUtil.isEmpty(userList)){
            //全部都下载了
            log.info("订单没有对应的负责人，无需发送提醒");
            return;
        }
        List<Long> userIds = userList.stream().map(User::getId).toList();
        List<LpsOrderDownload> downloadList = lpsOrderDownloadMapper.getDownloadList(orderId, userIds);
        if (CollUtil.isNotEmpty(downloadList)){
            List<Long> downloadUserIds = downloadList.stream().map(LpsOrderDownload::getUserId).toList();

            // 创建新列表而不是修改不可变列表
            userList = userList.stream()
                    .filter(user -> !downloadUserIds.contains(user.getId()))
                    .toList();
        }
        if (CollUtil.isEmpty(userList)){
            log.info("订单已全员下载完毕：{}",orderId);
            return;
        }
        List<LpsOrderDownload> lpsOrderDownloadList = userList.stream().map(user -> {
            LpsOrderDownload lpsOrderDownload = new LpsOrderDownload();
            lpsOrderDownload.setOrderId(lpsOrder.getId());
            lpsOrderDownload.setUserId(user.getId());
            //lpsOrderDownload.setUserName("");
            lpsOrderDownload.setDeptId(user.getDeptId());
            //lpsOrderDownload.setDeptName("");
            lpsOrderDownload.setFileName(lpsOrder.getFileName());
//            lpsOrderDownload.setRemark("");
//            lpsOrderDownload.setIsDownload(0);
//            lpsOrderDownload.setCreateBy(0L);
//            lpsOrderDownload.setUpdateBy(0L);
//            lpsOrderDownload.setIsDeleted(0);
            lpsOrderDownload.setId(IdUtil.getSnowflakeNextId());
            lpsOrderDownload.setCreateTime(LocalDateTime.now());
            lpsOrderDownload.setRemindTime(LocalDateTime.now());
            return lpsOrderDownload;
        }).toList();

        lpsOrderDownloadService.saveBatch(lpsOrderDownloadList);

        // 给未下载的用户发送消息
        for (User user : userList) {
            try {
                messagingTemplate.convertAndSendToUser(user.getUsername(), DESTINATION,new ChatMessage(SENDER, String.valueOf(1)));
                log.info("WebSocket发送订单提醒消息发送完成: 用户={}", user.getUsername());
            } catch (Exception e) {
                log.error("WebSocket发送订单提醒消息失败: 用户={}", user.getUsername(), e);
            }
        }
    }
}